package NIO;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ChannelAccept {

    public static String GREETING = "Hello World\r\n";

    public static void main(String[] args)throws Exception
    {
        System.out.println(Runtime.getRuntime().availableProcessors());
        int port = 1234;

        ServerSocketChannel ssc = ServerSocketChannel.open();

        ssc.socket().bind(new InetSocketAddress(port));

        ssc.configureBlocking(false);//非阻塞
//        ssc.configureBlocking(true);//阻塞

        while(true)
        {
            ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
            System.out.println("waiting for connecting....");

            SocketChannel sc = ssc.accept();

            if(null == sc)
            {
                Thread.sleep(3000);
            }else
            {
                System.out.println("Incoming connecting from : "+sc.socket().getRemoteSocketAddress());
                sc.write(buffer);
                sc.close();
            }

        }

    }

}
